import React, { useReducer, useEffect } from "react";

import { QueryContext, reducer } from '../store';
import { Config, JsonGroup, JsonPathGroup } from '../types';
import Group from "./item/Group";
import { addPathFromJsonGroup } from '../utils';

const QueryBuilder: React.FC<{
  config: Config,
  value?: JsonGroup,
  defaultValue?: JsonGroup,
  onChange?: (data: JsonGroup) => void
}> = (props) => {
  const { config, value, defaultValue = {
    condition: "OR",
    rules: [
      {
        id: void 0,
        field: void 0,
        type: void 0,
        input: void 0,
        operator: void 0,
        value: void 0,
      },
    ],
    not: false,
    valid: true
  }, onChange } = props;
  const [state, dispatch] = useReducer(reducer, value||defaultValue, (arg) => {
    if ((arg as unknown as JsonPathGroup).path) {
      return arg;
    } else {
      return addPathFromJsonGroup(arg);
    }
  });

  useEffect(() => {
    onChange && onChange(state);
  }, [state])

  return (
    <QueryContext.Provider value={{state, dispatch}}>
      <Group
        config={config}
        value={value}
      />
    </QueryContext.Provider>
  );
};

export default QueryBuilder;
